﻿using Enum;
using MediatR;
using Practice.API.Application.Commands.Roles;
using Practice.Common.Domains;
using Practice.Common.Dto;
using Practice.Common.Infrastructure.Interfaces;

namespace Practice.API.Application.Commands.UserW
{
    public class UserListHandler : IRequestHandler<UserListCommand, Result>
    {
        public readonly IBaseRepository<Users> UsersRepository;
        public readonly IBaseRepository<UserRole> UserRoleRepository;

        public UserListHandler(IBaseRepository<Users> usersRepository, IBaseRepository<UserRole> userRoleRepository)
        {
            UsersRepository = usersRepository;
            UserRoleRepository = userRoleRepository;
        }


        public async Task<Result> Handle(UserListCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.Success };
            try
            {
                var list = (from a in UsersRepository.GetAll()
                            join b in UserRoleRepository.GetAll() on a.UserId equals b.UserId
                            select new RoleListDto()
                            {
                               UserName=a.UserName,
                                Pwd=a.Pwd,
                                UserStatus =a.UserStatus,
                                UserId=b.UserId,
                                RoleId=b.RoleId,
                                UserRoleMassage= b.UserRoleMassage,
                                CreateTime = b.CreateTime
                            }).ToList();
                if (request.UserName != null)
                {
                    list = list.Where(x => x.UserName.Contains(request.UserName)).ToList();
                }

                result.Data = list;
                result.Code = (int)CommonEnumCode.Success;



            }
            catch (Exception)
            {

                result.Msg = "显示查询失败";

            }
            return result;
        }
    }
    public class RoleListDto
    {
        public string UserName { get; set; }
        public string Pwd { get; set; }
        public bool UserStatus { get; set; }
        public int UserId { get; set; }
        public string RoleId { get; set; }
        public string UserRoleMassage { get; set; }
        public string CreateTime { get; set; } = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
    }
}
